package org.syx.edl.support;

import cn.hutool.core.bean.BeanUtil;
import org.syx.edl.DelimitedLineTokenizer;
import org.syx.edl.LineMapper;

import javax.validation.ValidationException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author:whh
 * @date: 2025-09-06 00:37
 * <p></p>
 */
public class DefaultLineMapper <T> implements LineMapper<T> {

    private DelimitedLineTokenizer lineTokenizer;

    private Class<T> target;

    public DefaultLineMapper(DelimitedLineTokenizer lineTokenizer, Class<T> target) {
        this.lineTokenizer = lineTokenizer;
        this.target = target;
    }

    @Override
    public T mapLine(String line, int lineNumber) throws Exception {
        List<String> ls = lineTokenizer.doTokenize(line);
        Field[] fields = target.getDeclaredFields();
        if(ls.size()!=fields.length){
            throw new ValidationException("line length not match the target class field length, line :["+ls+"], class :["+target.getName()+"], field length: "+fields.length);
        }
        T t = target.newInstance();
        for (int i = 0; i < fields.length; i++) {
            BeanUtil.setFieldValue(t,fields[i].getName(),ls.get(i));
        }
        return t;
    }
}
